package com.qqtech.qquan.mall.service;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.frame.dao.BaseDao;
import com.qqtech.core.frame.service.BaseServiceImpl;
import com.qqtech.qquan.mall.dao.MallCommentDao;
import com.qqtech.qquan.mall.model.MallComment;
import com.qqtech.qquan.order.dao.OrderBaseDao;
import com.qqtech.qquan.order.dao.OrderItemDao;
import com.qqtech.qquan.order.enums.OrderBaseCommentStatusDictEnum;
import com.qqtech.qquan.order.model.OrderBase;
import com.qqtech.qquan.order.model.OrderItem;
import com.qqtech.qquan.order.model.OrderItemVo;

@Service
public class MallCommentServiceImpl extends BaseServiceImpl<MallComment>
		implements MallCommentService {
	public static final Logger log = LoggerFactory.getLogger(MallCommentServiceImpl.class);
	
	@Resource
	private MallCommentDao mallCommentDao;
	@Resource 
	private OrderBaseDao orderBaseDao;
	@Resource 
	private OrderItemDao orderItemDao;

	@Override
	protected BaseDao<MallComment> getBaseDao() {
		return mallCommentDao;
	}

	@Override
	public int handleSaveComment(MallComment mallComment) {
		int id = mallCommentDao.insert(mallComment);
		//更新订单明细 是否评价 TODO  合并成一个SQL
		OrderItem orderItemQeury = new OrderItem();
		orderItemQeury.setOrderNo(mallComment.getOrderNo());
		orderItemQeury.setProductId(mallComment.getProductId());
		OrderItemVo itemVo = orderItemDao.getOne(orderItemQeury);
		if(itemVo != null){
			OrderItem updateItem = new OrderItem();
			updateItem.setId(itemVo.getId());
			updateItem.setIsComment(YesNoEnum.YES.getCode());
			orderItemDao.updateById(updateItem);
		}
		
		//更新订单 评价状态
		OrderItem isCommentItemQeury = new OrderItem();
		isCommentItemQeury.setOrderNo(mallComment.getOrderNo());
		isCommentItemQeury.setIsComment(YesNoEnum.YES.getCode());
		//已评论的订单明细数量
		int isCommentCount = orderItemDao.queryCount(isCommentItemQeury);
		//订单明细总数
		OrderItem item = new OrderItem();
		item.setOrderNo(mallComment.getOrderNo());
		int orderItemCount = orderItemDao.queryCount(item);
		OrderBase ob = orderBaseDao.getByOrderNo(mallComment.getOrderNo());
		if(ob != null){
			OrderBase updateOrder = new OrderBase();
			updateOrder.setId(ob.getId());
			if(isCommentCount > 0){
				if(orderItemCount == isCommentCount){
					updateOrder.setCommentStatus(OrderBaseCommentStatusDictEnum.ALL.getCode());
				}else{
					updateOrder.setCommentStatus(OrderBaseCommentStatusDictEnum.PART.getCode());
				}
			}else{
				updateOrder.setCommentStatus(OrderBaseCommentStatusDictEnum.NONE.getCode());
			}
			//TODO 根据订单编号   更新状态
			orderBaseDao.updateById(updateOrder);
		}
		
		return id;
	}
	
}